<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模型边界线验证</title>
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.95/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        #cesiumContainer {
            width: 100%;
            height: 100vh;
            position: relative;
        }
        #controls {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }
        #debugInfo {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.9);
            padding: 10px;
            border-radius: 5px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div id="cesiumContainer"></div>
    <div id="controls">
        <button onclick="loadModelAndBoundary()">加载模型和边界</button>
        <button onclick="toggleBoundary()">显示/隐藏边界线</button>
        <div>
            <label>高度(米):</label>
            <input type="number" id="heightInput" value="100">
        </div>
        <div>
            <label>旋转角度(度):</label>
            <input type="number" id="rotationInput" value="0">
        </div>
        <div>
            <label>缩放比例:</label>
            <input type="number" id="scaleInput" value="1.0" step="0.1">
        </div>
    </div>
    <div id="debugInfo"></div>

    <script>
        // 使用新的有效 token
        Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzNzFlNTg1MC0wOTA0LTQzYzYtOTBjZi05MjIzZjU2NTkzZGQiLCJpZCI6MTE4ODE3LCJpYXQiOjE2NzE1MDY2NjF9.yGR3CbS6VQp2s6Y9NHWOIKq8qKL0sWLZZBZ9eP02Ags";

        // 初始化 Cesium viewer，使用更简单的配置
        const viewer = new Cesium.Viewer('cesiumContainer', {
            baseLayerPicker: false,
            geocoder: false,
            navigationHelpButton: false,
            homeButton: false,
            sceneModePicker: false,
            animation: false,
            timeline: false,
            fullscreenButton: false,
            infoBox: false,
            selectionIndicator: false
        });

        // 设置默认视图
        viewer.scene.globe.enableLighting = false;
        viewer.scene.globe.baseColor = Cesium.Color.WHITE;

        let modelEntity = null;
        let boundaryEntity = null;

        async function loadModelAndBoundary() {
            const height = parseFloat(document.getElementById('heightInput').value);
            const rotation = parseFloat(document.getElementById('rotationInput').value);
            const scale = parseFloat(document.getElementById('scaleInput').value);

            const modelConfig = {
                modelPath: "/person_000002.gltf",
                latitude: 39.9087202,
                longitude: 116.3974799,
                height: height,
                rotationX: rotation,
                rotationY: 0.0,
                rotationZ: 0.0,
                scale: scale
            };

            try {
                // 加载3D模型
                if (modelEntity) {
                    viewer.entities.remove(modelEntity);
                }

                modelEntity = viewer.entities.add({
                    position: Cesium.Cartesian3.fromDegrees(
                        modelConfig.longitude,
                        modelConfig.latitude,
                        modelConfig.height
                    ),
                    model: {
                        uri: modelConfig.modelPath,
                        scale: modelConfig.scale,
                        minimumPixelSize: 128,
                        maximumScale: 20000,
                        runAnimations: false,
                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                    }
                });

                // 计算并加载边界线
                const response = await fetch('http://localhost:8080/api/model/boundary', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(modelConfig)
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
                }

                const geoJson = await response.json();
                console.log('Received GeoJSON:', geoJson); // 调试输出

                // 检查 GeoJSON 数据结构
                if (!geoJson.features || !geoJson.features.length || 
                    !geoJson.features[0].geometry || 
                    !geoJson.features[0].geometry.coordinates || 
                    !geoJson.features[0].geometry.coordinates[0]) {
                    throw new Error('Invalid GeoJSON structure');
                }

                // 显示调试信息
                document.getElementById('debugInfo').innerText = 
                    `边界点数量: ${geoJson.features[0].geometry.coordinates[0].length}`;

                // 移除已有的边界线
                if (boundaryEntity) {
                    viewer.entities.remove(boundaryEntity);
                }

                // 提取坐标数组
                const coordinates = geoJson.features[0].geometry.coordinates[0];
                const positions = coordinates.map(coord => 
                    Cesium.Cartesian3.fromDegrees(
                        coord[0],
                        coord[1],
                        modelConfig.height
                    )
                );

                // 添加新的边界线
                boundaryEntity = viewer.entities.add({
                    polyline: {
                        positions: positions,
                        width: 5,
                        material: new Cesium.PolylineOutlineMaterialProperty({
                            color: Cesium.Color.RED.withAlpha(0.8),
                            outlineWidth: 2,
                            outlineColor: Cesium.Color.WHITE
                        }),
                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                        clampToGround: true
                    }
                });

                // 定位到模型
                viewer.zoomTo(modelEntity);

            } catch (error) {
                console.error('加载失败:', error);
                document.getElementById('debugInfo').innerText = `错误: ${error.message}`;
            }
        }

        function toggleBoundary() {
            if (boundaryEntity) {
                boundaryEntity.show = !boundaryEntity.show;
            }
        }

        // 初始化相机位置
        viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(116.3974799, 39.9087202, 1000),
            orientation: {
                heading: 0.0,
                pitch: -Math.PI/4,
                roll: 0.0
            }
        });

        // 移除默认的双击事件处理
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
            Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );
    </script>
</body>
</html> 